<?php
namespace Api\Provider\Admin;
use Api\Provider\IndexProvider;
use Api\Service\ScoreCommentService;
use Api\Service\SheetRecordService;
use Api\Service\UserMemberService;
use Common\Util\Wechat\WXBizDataCrypt;
use Api\Service\UserService;
use Common\Util\HttpClient;
use Think\Log;
/**
 * Description of ConstantProvider
 */
class UserProvider extends IndexProvider
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 公共配置参数获取
     * @param $param
     */
    public function user_info($param)
    {
        $service = new UserService();
        try{
            $service->validateParam($param);
        } catch(\Exception $e) {
            $this->fail(600, null, $e->getMessage());
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx0722be5b0604513f&secret=33b5ec5010f1bf145017fdb05b3f6ae6&js_code='.$param['code'].'&grant_type=authorization_code';
        $loginData= HttpClient::post($url);
        Log::writeInfo('start to execute save in UserProvider, param:' .$loginData,'user');
        $loginData = json_decode($loginData, true);
        if(empty($loginData['session_key'])) {
            $this->fail(10001001);
        }
        
        $sessionKey = $loginData['session_key'];
        
        $pc = new WXBizDataCrypt($sessionKey);
        $errCode = $pc->decryptData($param['encryptedData'], $param['iv'], $data );

        if ($errCode == 0) {
            //保存用户信息
            $user = $service->addUser($data);
            $this->success($user);
        } else {
            $this->fail($errCode);
        }
    }
     
    public function save($param) {
         
        $service = new UserService();
        $user = $service->addUser($param);
        $this->success($user);
    }

    /**
     * 获取个人中心信息
     */
    public function getUserInfo($param)
    {
        Log::writeInfo('start to getUserInfo in UserProvider, param:' .json_encode($param),'user');
        if (empty($param['uid'])) {
            $this->fail(600);
        }
        //获取用户信息
        $uid = $param['uid'];
        $res = M('User')->where(array('id'=>$uid))->field('id, nickname, avatar_url')->select();

        //获取评论总数
        $scoreInfo = M('Score')->where(array('creator'=>$uid))->field('id, name, creator, comment_count')->select();
        $scoreIds = array_column($scoreInfo,'id');
        $commentCount = array_sum(array_column($scoreInfo, 'comment_count'));
        $userInfo['userInfo'] = $res[0];
        $userInfo['userInfo']['commentCount'] = $commentCount;

        if ($userInfo) {
            $this->success($userInfo, 200);
        } else {
            $this->fail(500,'','暂无评论消息');
        }
    }

    /**
     * 获取个人中心录音列表
     */
    public function getUserRecord($param)
    {
        if (empty($param['uid'])) {
            $this->fail(600);
        }

        $service = new SheetRecordService();
        $list = $service->getUrlByParam($param);
        $this->success($list, 200);
    }

}